#= 音频的频谱分析（拟使用STFT和小波变换）
 @time: 2024/7/15 14:57
 @author: Eric Tian
=#
using FFTW, DSP, Plots
include("HelloAudio.jl")

function buf_to_spectrum(buf) # 会同时在 f 及 S-f 两个频率上产生强度（采样定理）
    return fft(buf)
end

devide_spec(spec) = spec[1:floor(Int, length(spec)/2)]

function find_fs_over_altitude(spec, altitude=500)
    # divided_spec = devide_spec(spec)
    return [domain(spec)[i]Hz for i in findall(x -> (abs(x) >= altitude), spec.data)]
end

function spec_analysis(data_or_buf)
    if data_or_buf isa Vector
        data_or_buf = to_buf(data_or_buf)
    end
    buf = data_or_buf
    spec = buf_to_spectrum(buf)
    dspec = devide_spec(spec)
    for k in find_fs_over_altitude(dspec)
        println(k)
    end
    plot(domain(dspec), abs.(dspec.data))
end

function plot_spectrogram(data, fs=S_num)
    spec = spectrogram(data[:,1], floor(Int, 25e-3*fs), floor(Int, 10e-3*fs); window=hanning)
    t = time(spec)
    f = freq(spec)
    return spec, heatmap(t/fs,fs*f*Hz,log10.(power(spec)))
end